package com.boang.ks;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class GradeManager {
    private List<Student> students;
    private ReentrantLock lock;

    public GradeManager() {
        this.students = new ArrayList<>();
        this.lock = new ReentrantLock();
    }

    //添加成绩
    public void addGrade(Student student) throws DuplicateStudentException {
        lock.lock();
        try {
            for (Student s : students) {
                if (s.equals(student)) {
                    throw new DuplicateStudentException("Student with name " + student.getName() + " already exists.");
                }
            }
            students.add(student);
        } finally {
            lock.unlock();
        }
    }

    //计算平均分
    public double calculateAverage() {
        lock.lock();
        try {
            if (students.isEmpty()) {
                return 0;
            }
            double total = 0;
            for (Student s : students) {
                total += s.getScore();
            }
            return total / students.size();
        } finally {
            lock.unlock();
        }
    }

    //计算最高分
    public double findHighest() {
        lock.lock();
        try {
            if (students.isEmpty()) {
                throw new IllegalStateException("No grades to find the highest.");
            }
            double highest = Double.NEGATIVE_INFINITY;
            for (Student s : students) {
                if (s.getScore() > highest) {
                    highest = s.getScore();
                }
            }
            return highest;
        } finally {
            lock.unlock();
        }
    }

    //计算最低分
    public double findLowest() {
        lock.lock();
        try {
            if (students.isEmpty()) throw new IllegalStateException("No grades to find the lowest.");
            double lowest = Double.POSITIVE_INFINITY;
            for (Student s : students) {
                if (s.getScore() < lowest) {
                    lowest = s.getScore();
                }
            }
            return lowest;
        } finally {
            lock.unlock();
        }
    }
}